package com.project.controller;

import com.project.controller.viewobject.UserVO;
import com.project.dao.UserDOMapper;
import com.project.response.CommonResponse;
import com.project.service.UserService;
import com.project.service.model.UserModel;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;


@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserDOMapper userDOMapper;

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse userLogin(@RequestParam(name = "telphone")String telphone,
                                    @RequestParam(name = "password")String password){
        if (telphone == null || password == null){
            return new CommonResponse("参数不正确",null);
        }

        UserModel userModel = userService.userLogin(telphone,password);
        UserVO userVO = this.convertFromUserModel(userModel);

                return new CommonResponse("success",userVO);
    }

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse userRegister(@RequestParam(name = "telphone")String telphone,
                                    @RequestParam(name = "password")String password,
                                       @RequestParam(name = "mailAddress")String mailAddress){
        if (telphone == null || password == null){
            return new CommonResponse("参数不正确",null);
        }

        if (userService.userRegister(telphone,password,mailAddress)){
            return new CommonResponse("success",null);
        }
        return new CommonResponse("failed",null);
    }

    @RequestMapping(value = "/prePaidService", method = RequestMethod.POST)
    @ResponseBody
    public CommonResponse prePaidService(@RequestParam(name = "userId")Integer userId,
                                         @RequestParam(name = "total")Integer total){
        // 参数校验
        if (userId == null || total == null){
            return CommonResponse.create(null,"参数错误");
        }
       // 调用接口写入数据库
        userService.prePaid(userId,total);
        return CommonResponse.create(null,"success");
    }

    private UserVO convertFromUserModel(UserModel userModel){
        if (userModel == null){
            return null;
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(userModel,userVO);
        return userVO;
    }
}
